﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using TelecoSystems.Infrastructure.Helpers;
using TelecoSystems.Web;
using System.ServiceModel.DomainServices.Client;
using TelecoSystems.Infrastructure.Views;
using Microsoft.Practices.Composite.Presentation.Commands;
using System.ComponentModel;

namespace TelecoSystems.Modules.Administration.ViewModels {
    public class UsersViewModel : PagedViewModelBase {
        #region Fields
        private AuthenticationContext _authContext;
        #endregion

        #region Constructors
        public UsersViewModel(AuthenticationContext authContext) {
            _authContext = authContext;

            Users = new PagedEntityCollectionView<User>(_authContext.Users, this);

            SubmitChangesCommand = new DelegateCommand<object>(SubmitChanges, CanSubmitChanges);
            RejectChangesCommand = new DelegateCommand<object>(RejectChanges, CanRejectChanges);

            LoadData();
        }
        #endregion

        #region Data
        public override void LoadData() {
            if (IsLoading || _authContext == null) {
                return;
            }

            IsBusy = true;
            IsLoading = true;

            _authContext.Users.Clear();
            var q = _authContext.GetAllUsersQuery();

            _authContext.Load(q, UsersLoaded, null);
        }
        #endregion

        #region VM Properties
        public string HeaderInfo { get { return "Users administration"; } }

        private PagedEntityCollectionView<User> _users;
        public PagedEntityCollectionView<User> Users {
            get { return _users; }
            set {
                if (_users != value) {
                    _users = value;
                    NotifyPropertyChanged("Users");
                }
            }
        }

        private User _userDetail;
        public User UserDetail {
            get { return _userDetail; }
            set {
                if (_userDetail != value) {
                    _userDetail = value;
                    //_userDetail.PropertyChanged += (s, e) => {
                    //    if (SubmitChangesCommand != null)
                    //        SubmitChangesCommand.Execute(null);
                    //};
                    if (SubmitChangesCommand != null)
                        SubmitChangesCommand.RaiseCanExecuteChanged();
                    NotifyPropertyChanged("UserDetail");                    
                }                
            }
        }

        private bool _isBusy = false;
        public bool IsBusy {
            get { return _isBusy; }
            set {
                if (_isBusy != value) {
                    _isBusy = value;
                    NotifyPropertyChanged("IsBusy");
                }
            }
        }

        private string _busyContent = "Please wait...";
        public string BusyContent {
            get { return _busyContent; }
            set {
                if (_busyContent != value) {
                    _busyContent = value;
                    NotifyPropertyChanged("BusyContent");
                }
            }
        }
        #endregion

        #region Commands
        #region SubmitChanges
        public DelegateCommand<object> SubmitChangesCommand { get; set; }
        void SubmitChanges(object o) {
            if (!_authContext.IsSubmitting) {                                                
                IsBusy = true;
                foreach (User user in _authContext.Users) {
                    if (user.EntityState == EntityState.Modified) {
                        ((IRevertibleChangeTracking)user).AcceptChanges();
                        user.UpdateTheUser();                        
                    }
                }
                
                _authContext.SubmitChanges(SubmitChangesCompleted, null);
            }
        }
        bool CanSubmitChanges(object o) {
            bool r = _authContext.HasChanges || ((UserDetail != null) ? UserDetail.HasChanges : false);
            return true;
        }
        #endregion

        #region RejectChanges
        public DelegateCommand<object> RejectChangesCommand { get; set; }
        void RejectChanges(object o) {
            _authContext.RejectChanges();
        }
        bool CanRejectChanges(object o) {
            return _authContext.HasChanges || ((UserDetail != null) ? UserDetail.HasChanges : false);
        }
        #endregion
        #endregion

        #region Event Handlers
        private void UsersLoaded(LoadOperation<User> loadOperation) {
            if (loadOperation.HasError) {
                ErrorWindow.CreateNew(loadOperation.Error, StackTracePolicy.OnlyWhenDebuggingOrRunningLocally);
            } else {
                Users.MoveCurrentToFirst();

                ItemCount = loadOperation.TotalEntityCount;
                TotalItemCount = loadOperation.TotalEntityCount;
                InformationWindow.Create("Users were loaded successfully.", "Notification");
            }
            IsLoading = false;
            IsBusy = false;
        }

        private void SubmitChangesCompleted(SubmitOperation submit) {
            if (submit.HasError) {
                foreach (Entity entity in submit.EntitiesInError) {

                }
                ErrorWindow.CreateNew(submit.Error, StackTracePolicy.OnlyWhenDebuggingOrRunningLocally);
            } else {
                InformationWindow.Create("Changes were saved successfully.", "Information");
            }
            IsBusy = false;
        }
        #endregion
    }
}
